package com.ityuwen.mengyagushi.live.config;

import com.alibaba.fastjson.JSON;
import com.ityuwen.mengyagushi.model.live.SocketMsg;
import jakarta.websocket.Session;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChartRoomContainer {

    // 以直播间的id作为key（一个直播间相当于一个聊天室），可能同时存在多个直播间或者聊天室
    private static Map<Long, List<Long>> userMap = new ConcurrentHashMap<>();

    // 以用户的id作为key，以用户的session会话对象作为value
    private static Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 用户加入直播间
     * @param roomId
     * @param userId
     * @param session
     */
    public static void addUser(Long roomId, Long userId, Session session){
        // 获取该直播间用户id集合
        List<Long> userIds = userMap.get(roomId);
        if (userIds == null) {
            userIds = new ArrayList<>();
            userMap.put(roomId, userIds);
        }
        userIds.add(userId);
        sessionMap.put(userId, session);
    }

    /**
     * 用户离开了直播间
     * @param roomId
     * @param userId
     */
    public static void removeUser(Long roomId, Long userId){
        List<Long> userIds = userMap.get(roomId);
        if (userIds == null) {
            return ;
        }
        userIds.remove(userId);
        sessionMap.remove(userId);
    }

    /**
     * 获取直播间用户列表
     */
    public static List<Long> getUser(Long roomId){
        List<Long> userIds = userMap.get(roomId);
        return userIds;
    }

    /**
     * 获取直播间人数
     * @param roomId
     * @return
     */
    public static Integer getUserCount(Long roomId){
        List<Long> userIds = getUser(roomId);
        if (userIds == null){
            return 0;
        }
        return userIds.size();
    }

    public static void sendMsg(String msg){ // 用户通过websocket发送的是文本消息
        // 如果消息不为空
        if (StringUtils.isBlank(msg)){
            return;
        }
        // 反序列化为空SocketMsg对象
        SocketMsg socketMsg = JSON.parseObject(msg, SocketMsg.class);
        if (socketMsg == null || socketMsg.getMsgType().equals(SocketMsg.MsgTypeEnum.HEART_BEAT.getCode())){
            return;
        }
        // 正常消息
        Long roomId = socketMsg.getLiveRoomId();
        List<Long> userIds = userMap.get(roomId);
        if (userIds == null) {
            return;
        }
        // 遍历直播间所有用户，获取session，通过session推送消息
        userIds.forEach(userId -> {
            Session session = sessionMap.get(userId);
            if (session != null) {
                session.getAsyncRemote().sendText(JSON.toJSONString(socketMsg));
            }
        });
    }
}
